import React, { Component } from "react";
import { Form, Button, Modal, Transfer, message, Tag, Tabs, List } from "antd";
import { CheckCircleOutlined, MinusCircleOutlined } from "@ant-design/icons";
import axios from "axios";
import qs from "qs";
import OrgTree from "./OrgTree";
import "../mock/user003001";
import "../mock/user003002";
import "../mock/group";
import "../mock/groupMembers";
const { TabPane } = Tabs;

export default class EditJoin extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      addVisible: false,
      //   mockData: ["李亮", "张明", "李飞", "王培"], //职工列表
      enableMockData: [], //职工列表
      enableTargetKeys: props.record.enable,
      //   hostSelectedKeys: [props.record.meetingHost],
      //   joinSelectedKeys: [props.record.meetingJoin],
      rules: [
        {
          required: false,
          message: "此项不可为空",
        },
      ],
      treeData: [],
      getDataSource: props.getDataSource,
      personnelGroup: [],
    };
    this.formRef = React.createRef();
    this.setTreeData = this.setTreeData.bind(this);
    this.treeOnSelect = this.treeOnSelect.bind(this);
  }

  /**添加主持人 */
  handleHostChange = (hostTargetKeys) => {
    this.setState({ hostTargetKeys });
  };
  /**添加参会人 */
  handleEnableChange = (enableTargetKeys) => {
    this.setState({ enableTargetKeys });
  };
  /**机构数据 */
  setTreeData = (treeData) => {
    setTimeout(() => {
      this.setState({ treeData });
    }, 0);
  };

  /*点击部门列表,展示部门人员 */
  treeOnSelect = (value) => {
    console.log(value);
    // this.getMock(isHost, value);
    axios
      .get("../weekmeeting/searchUsers.rst?orgId=" + value[0])
      .then((res) => {
        let response = res.data;
        // response = response.data;
        console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */

          this.setState({
            enableMockData: res.map((person) => {
              return {
                key: person.EMPID + "_" + person.EMPNAME,
                title: person.EMPID + "_" + person.EMPNAME,
              };
            }),
          });
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  /**弹出对话框 */
  showAddModal = () => {
    console.log(this.state.enableTargetKeys);
    const record = this.props.record;
    /**弹出 */
    this.setState({
      addVisible: true,
    });
    /**等待form渲染 */
    setTimeout(() => {
      this.formRef.current.setFieldsValue({
        address: record.meetingAddress,
        content: record.meetingContent,
        meetingRoom: record.meetingRoom,
      });
    }, 100);
  };

  onFinish = (values) => {
    /**表单字段在不做改动时返回时会为undefined，需要手动判断 */

    let pass = true;
    let messCon = "";
    /**表单返回值 currVal*/
    const currVal = this.formRef.current.getFieldsValue();
    console.log(currVal);
    // console.log(currVal)
    /**判断日期，地点，内容 */

    /**判断主持人和参会人 */

    if (this.state.enableTargetKeys.length === 0) {
      pass = false;
      messCon = "分享范围";
    }

    /** */
    if (pass) {
      this.setState({ loading: true });
      /**修改活动数据 */
      axios({
        url: "../weekmeeting/updatemeeting.rst",
        method: "post",
        data: qs.stringify({
          id: this.props.record.key,
          person: this.state.enableTargetKeys.join(),
          enable: 1,
        }),
      })
        .then((res) => {
          let response = res.data;
          if (response.resultCode === 0) {
            /**清空并关闭添加表单 */
            message.success("提交成功");
            this.setState({ loading: false, addVisible: false });
            /**重新渲染活动列表 */
            this.props.getDataSource();
          } else {
            message.error("提交失败");
          }
        })
        .catch((error) => {
          message.error("提交失败");
        });
    } else {
      /**有字段为空 */
      message.error(messCon + "字段不可为空！");
    }
  };

  handleCancel = () => {
    const { enable } = this.props.record;
    /**清空修改表单状态 */
    // this.formRef.current.resetFields();
    this.setState({
      enableTargetKeys: enable,
    });
    this.setState({ loading: false, addVisible: false });
  };

  /*获取人员组数据 */
  getPersonnelGroup = () => {
    axios
      .get("../weekmeeting/group.rst")
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            personnelGroup: res.map((group) => {
              return {
                label: group.groupName,
                value: group.groupName,
                groupId: group.groupId,
              };
            }),
          });
        } else {
          // message.error("人员组请求失败");
        }
      })
      .catch((error) => {
        message.error("人员组请求失败");
      });
  };

  /**选择人员组 */
  personnelGroupOnClick = (item) => {
    // console.log(item.member);
    axios
      .get("../weekmeeting/groupMembers.rst?groupId=" + item.groupId)
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            enableMockData: res.map((person) => {
              return {
                key: person.EMPID + "_" + person.EMPNAME,
                title: person.EMPID + "_" + person.EMPNAME,
              };
            }),
          });
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  componentDidMount() {
    this.getPersonnelGroup();
  }
  /**关闭Tag */

  handleEnableTagClose = (removedTag) => {
    const enableTargetKeys = this.state.enableTargetKeys.filter(
      (enableTargetKeys) => enableTargetKeys !== removedTag
    );
    console.log(enableTargetKeys);
    this.setState({ enableTargetKeys });
  };
  /*遍历插入Tag */
  enableForMap = (tag) => {
    // console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="blue"
          onClose={(e) => {
            e.preventDefault();
            this.handleEnableTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };

  render() {
    /**添加活动数据 */
    const {
      addVisible,
      loading,
      personnelGroup,
      rules,
      enableMockData,
      enableTargetKeys,
      treeData,
    } = this.state;
    const enableTag = enableTargetKeys.map(this.enableForMap);
    // let enableLength = enableTargetKeys.length;
    return (
      <>
        {/* <Button type="primary" onClick={this.showAddModal}>
          修改
        </Button> */}
        <span className="editJoin" onClick={this.showAddModal}>
          {/* {enableTargetKeys} */}
          <Tag
            icon={
              this.props.record.isEnable === 1 ? (
                <CheckCircleOutlined />
              ) : (
                <MinusCircleOutlined />
              )
            }
            color={this.props.record.isEnable === 1 ? "#87d068" : "default"}
          >
            {this.props.record.isEnable === 1 ? "启用" : "未启用"}
          </Tag>
        </span>
        <Modal
          visible={addVisible}
          title="请选择分享范围"
          centered
          onCancel={this.handleCancel}
          //   onOk={this.handleAdd}
          width={1000}
          //   onCancel={this.handleCancel}
          footer={null}
        >
          <Form
            name="add-meeting"
            onFinish={this.onFinish}
            className="search-meet"
            ref={this.formRef}
          >
            <Form.Item
              name="enable"
              label=""
              rules={rules}
              className="enableSelect"
            >
              {enableTag}

              <Tabs
                defaultActiveKey="1"
                type="card"
                size="small"
                className="OrgTreeTab"
              >
                <TabPane tab="人员机构" key="1">
                  <OrgTree
                    treeData={treeData}
                    setTreeData={this.setTreeData}
                    treeOnSelect={this.treeOnSelect}
                  />
                </TabPane>
                <TabPane tab="人员组" key="2">
                  <List
                    className="personnelGroup"
                    size="small"
                    itemLayout="horizontal"
                    dataSource={personnelGroup}
                    renderItem={(item) => (
                      <List.Item>
                        <List.Item.Meta
                          title={item.value}
                          member={item.member}
                          onClick={() => this.personnelGroupOnClick(item)}
                        />
                      </List.Item>
                    )}
                  />
                </TabPane>
              </Tabs>

              <Transfer
                dataSource={enableMockData}
                targetKeys={enableTargetKeys}
                // selectedKeys={joinTargetKeys}
                showSearch
                listStyle={{
                  width: 250,
                  height: 200,
                }}
                operations={["添加", "移出"]}
                onChange={this.handleEnableChange}
                render={(item) => item.title}
              />
            </Form.Item>

            <Button type="primary" htmlType="submit" loading={loading}>
              确定
            </Button>
          </Form>
        </Modal>
      </>
    );
  }
}
